package com.javacoo.xservice.base.support.event;

import java.util.Optional;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

/**
 * 获取applicationContext
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年7月3日上午9:52:55
 */
@Configuration
public class ApplicationContextProvider implements ApplicationContextAware {  
    private static ApplicationContext ctx = null;  
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)  
            throws BeansException {  
        ctx = applicationContext;  
    }  
  
    public static ApplicationContext getApplicationContext() {  
        return ctx;  
    }

    public static <T> T getBean(Class<T> type) {
        try {
            return Optional.ofNullable(ctx).orElseThrow(() -> new IllegalStateException("non in spring application context.")).getBean(type);
        } catch (Exception e) {
            return null;
        }
    }
    public static void registerBean(String beanName,Object object){
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) ctx;

        configurableApplicationContext.getBeanFactory().registerSingleton(beanName, object);
    }

}
